import { Logger, LogFactory } from "./log";
import { Redis } from './redis';

export type RealMsgCallback = (channel:string, message:string) => void;

export class RealMsg{
    log:Logger = LogFactory.inst().getLogger("RealMsg");
    rcSend:Redis;
    rcRecv:Redis;

    constructor(host:string, port:number){
        this.rcSend = new Redis(host, port);
        this.rcRecv = new Redis(host, port);
    }

    async publish(channel:string, msg:string):Promise<boolean>{
        return new Promise<boolean>((resolve, reject)=>{
            this.rcSend.rc.publish(channel, msg, (err: Error | null, reply: number) => {
                if (err){
                    this.log.error("error:", err);
                    reject(err);
                }else{
                    resolve(true);
                }
            });
        });
    }

    async subscribe(channel:string, callback:RealMsgCallback):Promise<boolean>{
        return new Promise<boolean>((resolve, reject)=>{
            this.rcRecv.rc.subscribe(channel, (err: Error | null, reply: string) => {
                if (err){
                    this.log.error("error:", err);
                    reject(err);
                }else{
                    this.rcRecv.rc.on("message", (c: string, m: string) => {
                        if (c == channel){
                            callback(channel, m);
                        }
                    });
                    resolve(true);
                }
            });
        });
    }
}